package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysStation;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysStationMapper;
import com.ruoyi.system.service.ISysStationService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 工站管理 服务实现
 * 
 * @author ruoyi
 */
@Service
public class SysStationServiceImpl implements ISysStationService
{
    @Autowired
    private SysStationMapper stationMapper;

    /**
     * 查询工站管理数据
     * 
     * @param station 工站信息
     * @return 工站信息集合
     */
    @Override
    @DataScope(stationAlias = "d")
    public List<SysStation> selectStationList(SysStation station)
    {
        return stationMapper.selectStationList(station);
    }

    /**
     * 查询工站管理树
     * 
     * @param station 工站信息
     * @return 所有工站信息
     */
    @Override
    @DataScope(stationAlias = "d")
    public List<Ztree> selectStationTree(SysStation station)
    {
        List<SysStation> stationList = stationMapper.selectStationList(station);
        List<Ztree> ztrees = initZtree(stationList);
        return ztrees;
    }

    /**
     * 查询工站管理树（排除下级）
     * 
     * @param station 工站ID
     * @return 所有工站信息
     */
    @Override
    @DataScope(stationAlias = "d")
    public List<Ztree> selectStationTreeExcludeChild(SysStation station)
    {
        Long stationId = station.getStationId();
        List<SysStation> stationList = stationMapper.selectStationList(station);
        Iterator<SysStation> it = stationList.iterator();
        while (it.hasNext())
        {
            SysStation d = (SysStation) it.next();
            if (d.getStationId().intValue() == stationId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), stationId + ""))
            {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(stationList);
        return ztrees;
    }

    /**
     * 根据角色ID查询工站（数据权限）
     *
     * @param role 角色对象
     * @return 工站列表（数据权限）
     */
    @Override
    public List<Ztree> roleStationTreeData(SysRole role)
    {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysStation> stationList = selectStationList(new SysStation());
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleStationList = stationMapper.selectRoleStationTree(roleId);
            ztrees = initZtree(stationList, roleStationList);
        }
        else
        {
            ztrees = initZtree(stationList);
        }
        return ztrees;
    }

    /**
     * 对象转工站树
     *
     * @param stationList 工站列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysStation> stationList)
    {
        return initZtree(stationList, null);
    }

    /**
     * 对象转工站树
     *
     * @param stationList 工站列表
     * @param roleStationList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysStation> stationList, List<String> roleStationList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleStationList);
        for (SysStation station : stationList)
        {
            if (UserConstants.DEPT_NORMAL.equals(station.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(station.getStationId());
                ztree.setpId(station.getParentId());
                ztree.setName(station.getStationName());
                ztree.setTitle(station.getStationName());
                if (isCheck)
                {
                    ztree.setChecked(roleStationList.contains(station.getStationId() + station.getStationName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询工站人数
     * 
     * @param parentId 工站ID
     * @return 结果
     */
    @Override
    public int selectStationCount(Long parentId)
    {
        SysStation station = new SysStation();
        station.setParentId(parentId);
        return stationMapper.selectStationCount(station);
    }

    /**
     * 查询工站是否存在用户
     * 
     * @param stationId 工站ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkStationExistUser(Long stationId)
    {
        int result = stationMapper.checkStationExistUser(stationId);
        return result > 0 ? true : false;
    }

    /**
     * 删除工站管理信息
     * 
     * @param stationId 工站ID
     * @return 结果
     */
    @Override
    public int deleteStationById(Long stationId)
    {
        return stationMapper.deleteStationById(stationId);
    }

    /**
     * 新增保存工站信息
     * 
     * @param station 工站信息
     * @return 结果
     */
    @Override
    public int insertStation(SysStation station)
    {
        SysStation info = stationMapper.selectStationById(station.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new BusinessException("工站停用，不允许新增");
        }
        station.setAncestors(info.getAncestors() + "," + station.getParentId());
        return stationMapper.insertStation(station);
    }

    /**
     * 修改保存工站信息
     * 
     * @param station 工站信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStation(SysStation station)
    {
        SysStation newParentStation = stationMapper.selectStationById(station.getParentId());
        SysStation oldStation = selectStationById(station.getStationId());
        if (StringUtils.isNotNull(newParentStation) && StringUtils.isNotNull(oldStation))
        {
            String newAncestors = newParentStation.getAncestors() + "," + newParentStation.getStationId();
            String oldAncestors = oldStation.getAncestors();
            station.setAncestors(newAncestors);
            updateStationChildren(station.getStationId(), newAncestors, oldAncestors);
        }
        int result = stationMapper.updateStation(station);
        if (UserConstants.DEPT_NORMAL.equals(station.getStatus()))
        {
            // 如果该工站是启用状态，则启用该工站的所有上级工站
            updateParentStationStatus(station);
        }
        return result;
    }

    /**
     * 修改该工站的父级工站状态
     * 
     * @param station 当前工站
     */
    private void updateParentStationStatus(SysStation station)
    {
        String updateBy = station.getUpdateBy();
        station = stationMapper.selectStationById(station.getStationId());
        station.setUpdateBy(updateBy);
        stationMapper.updateStationStatus(station);
    }

    /**
     * 修改子元素关系
     * 
     * @param stationId 被修改的工站ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateStationChildren(Long stationId, String newAncestors, String oldAncestors)
    {
        List<SysStation> children = stationMapper.selectChildrenStationById(stationId);
        for (SysStation child : children)
        {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            stationMapper.updateStationChildren(children);
        }
    }

    /**
     * 根据工站ID查询信息
     * 
     * @param stationId 工站ID
     * @return 工站信息
     */
    @Override
    public SysStation selectStationById(Long stationId)
    {
        return stationMapper.selectStationById(stationId);
    }

    /**
     * 根据ID查询所有子工站（正常状态）
     * 
     * @param stationId 工站ID
     * @return 子工站数
     */
    @Override
    public int selectNormalChildrenStationById(Long stationId)
    {
        return stationMapper.selectNormalChildrenStationById(stationId);
    }

    /**
     * 校验工站名称是否唯一
     * 
     * @param station 工站信息
     * @return 结果
     */
    @Override
    public String checkStationNameUnique(SysStation station)
    {
        Long stationId = StringUtils.isNull(station.getStationId()) ? -1L : station.getStationId();
        SysStation info = stationMapper.checkStationNameUnique(station.getStationName(), station.getParentId());
        if (StringUtils.isNotNull(info) && info.getStationId().longValue() != stationId.longValue())
        {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }
}
